package com.bifrost.service.impl;

import com.bifrost.service.FileService;
import com.bifrost.service.TransactionService;
import com.bifrost.task.support.FTPClientPool;
import com.bifrost.task.support.FtpConnectWrapper;
import com.bifrost.util.FTPUtil;
import com.bifrost.util.FTPUtilForCDN;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * Author by yanxiaobo
 * Date on 2018/12/20$.
 */
@Service
public class FileServiceImpl implements FileService {
    Logger logger = LoggerFactory.getLogger(TransactionService.class);

    @Autowired
    @Qualifier("mediaFTPClientPool")
    FTPClientPool ftpClientPool;

    @Override
    public boolean upload(File file, String remote, boolean deleteAfterUpload) {
        boolean result = false;
        FtpConnectWrapper ftpConnectWrapper = null;
        try {
            ftpConnectWrapper = ftpClientPool.borrowObject();
            result = FTPUtilForCDN.upload(file, remote, ftpConnectWrapper);
        } catch (Exception e) {
                e.printStackTrace();
        } finally {
            if (null != file && deleteAfterUpload)
                file.delete();
            try {
                if (null != ftpConnectWrapper)
                    ftpClientPool.returnObject(ftpConnectWrapper);
            } catch (Exception e) {
                logger.error("归还ftp连接出错：{}", e);
                throw new RuntimeException("归还ftp连接出错");
            }
        }
        return result;
    }

}
